require('dotenv').config();
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');

var indexRouter = require('./routes/index');
var adminArticlesRouter = require('./routes/admin/articles');
var adminCategoriesRouter = require('./routes/admin/categories');
var adminSettingsRouter = require('./routes/admin/settings');
var adminUsersRouter = require('./routes/admin/users');
var adminCoursesRouter = require('./routes/admin/courses');
var adminChaptersRouter = require('./routes/admin/chapters');
var statisticsRouter = require('./routes/admin/statistics');
var authRouter = require('./routes/admin/auth');

// 引入认证中间件
const { auth } = require('./middleware/auth');

var app = express();

// CORS 配置
const corsOptions = {
    origin: process.env.ALLOWED_ORIGINS ? process.env.ALLOWED_ORIGINS.split(',') : '*',
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization'],
    credentials: true,
    maxAge: 86400 // 预检请求缓存24小时
};

app.use(cors(corsOptions));

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/auth', authRouter);
// 后台管理
app.use('/api/*', auth);
app.use('/admin/*', auth);
app.use('/', indexRouter);
app.use('/admin/articles', adminArticlesRouter);
app.use('/admin/categories', adminCategoriesRouter);
app.use('/admin/settings', adminSettingsRouter);
app.use('/admin/users', adminUsersRouter);
app.use('/admin/courses', adminCoursesRouter);
app.use('/admin/chapters', adminChaptersRouter);
app.use('/admin/statistics', statisticsRouter);

// 错误处理中间件
app.use((err, req, res, next) => {
    console.error('Error:', err);
    res.status(500).json({
        status: 500,
        message: '服务器内部错误',
        error: err.message
    });
});

module.exports = app;
